function setDate(objEnddate, days){
    var dt = new Date(parseInt($dp.cal.getP('y')), parseInt($dp.cal.getP('M'))-1, parseInt($dp.cal.getP('d'))+days);
    objEnddate.value = dt.format("yyyy-MM-dd");
}


$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		
		$("#orderItemsTable").jqGrid({						
			url : appRoot + '/expenseApplyItem/list/' + expenseApplyId + '?ajax=1',
			editurl : appRoot + '/expenseApplyItem/save?ajax=1&expenseApplyId=' + expenseApplyId,
			datatype : 'json',
			mtype : 'GET',
			jsonreader: {             
				repeatitems: false,
				id:'Id',
				root:'rows'
			}, 
			colNames : [ 'id','objectId','款项', '请款金额', '收款人', '支付方式','帐号名称','帐号','银行名称','支行'],
			colModel : [
	       {
				name : 'id',
				index : 'id',
				editable : true,
				hidden:true
				
			}, {
				name : 'objectId',
				index : 'objectId',
				editable : true,
				hidden:true
			},
			{
				name : 'reason',
				index : 'reason',
				width : 150,
				align : 'left',
				resizable : false,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}

			}, {
				name : 'amount',
				index : 'amount',
				width : 40,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}
			}, {
				name : 'receiver',
				index : 'receiver',
				width : 50,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}
			}, {
				name : 'type',
				index : 'type',
				width : 30,
				align : 'right',
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :"1:现金;2:转帐"
			    },
				editrules : {
					required : true,
					number : false
				}
			}, {
				name : 'bankAccountName',
				index : 'bankAccountName',
				width : 120,
				align : 'right',
				edittype:'textarea',
				editable : true,
				sortable: false,
				editrules : {
					number : false
				}
			}, {
				name : 'bankNo',
				index : 'bankNo',
				width : 120,
				align : 'right',
				edittype:'textarea',
				editable : true,
				sortable: false,
				editrules : {
					number : false
				}
			}, {
				name : 'bankName',
				index : 'bankName',
				width : 120,
				align : 'right',
				edittype:'textarea',
				editable : true,
				sortable: false,
				editrules : {
					number : false
				}
			}, {
				name : 'bankBranchName',
				index : 'bankBranchName',
				width : 120,
				align : 'right',
				edittype:'textarea',
				editable : true,
				sortable: false,
				editrules : {
					number : false
				}
			}
			],
			gridComplete: function(){
				var grid = $("#orderItemsTable");
				var sumAmount = grid.jqGrid('getCol', 'amount', false, 'sum'); 
				grid.jqGrid('footerData','set', {reason:"合计:",amount:sumAmount}); 
			},
			width: 730,
			height : 400,
			pager : $('#pager'),
			nowNum : 100,
			rowNum : 100,
			sortname : 'id',
			viewrecords : true,
			footerrow: true,
			caption : '明细'
		}).navGrid("#pager",{edit:true,add:true,del:true,search:false});
		
	}catch(e){}
	
	$(".colorbox").colorbox({iframe:true, innerWidth:700, innerHeight:460});

	function typeFmatter(el, cellval, opts) {
	    if(el=="1"){
	         return "现金";
	     }else if (el==2) {
	        return "转帐";
	     }
	}
	 
	function typeUFmatter(el, opts) {
	    if(el=="现金"){
	        return "1";
	    }else if(el=="转帐") {
	        return "2";
	    }
	}
});
//page
function getOrderCustomer(id){
    $("#suberror").hide();
    $("#subnotice").hide();
    $("#otherUsers").val("");
    $("input[type='checkbox']").each(function(){
        $(this).attr("checked",false);
    });
    if(id){
        $.ajax({
             url: appRoot + "/order/getCustomer/" + id,
             type:'post',
             dataType:'json',
             success:function(msg){
                 $("#customer_2").text(msg.entity.name).attr("title",msg.entity.email);
             }
        });
    }
}

function notify(){
    if(currentOrderId==null){
        return;
    }
    $(".audit").attr("disabled",true);
    $("#notifyButton").attr("disabled",true);
    var selected = getCheckedValuesString(document.getElementsByName("users"));
    var customer = ($("#customer_1").attr("checked")=="checked");
    var others = $("#otherUsers").val();
    if(!selected&&!customer&&!others){
        $("#suberror").html("请至少选择一个接收者").show();
        $(".audit").attr("disabled",false);
        $("#notifyButton").attr("disabled",false);
    }else{
        $("#suberror").hide();
        $("#subnotice").html("操作进行中...").show();
        $.ajax({
             url: appRoot + "/expenseApply/notify/" + currentOrderId + "?date=" + (new Date()).valueOf(),
             type:'post',
             dataType:'json',
             data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
             success:function(msg){
                 if(msg.result){
                     showMessage("邮件已发送");
                 }else{
                     showMessage("操作失败");
                 }
                 $(".audit").attr("disabled",false);
                 $("#notifyButton").attr("disabled",false);
                 jQuery.fn.colorbox.close();
             }
        });
    }
}

function audit(orderId,action){
	$("#notice").html("操作进行中...").show();
    $(".audit").attr("disabled",true);
    $.ajax({
         url: appRoot + "/expenseApply/audit/" + orderId,
         type:'post',
         dataType:'json',
         data:"status=20" ,
         success:function(msg){
             if(msg.result){
                 window.location.href= appRoot + '/expenseApply/' + action + '?message=' + encodeURIComponent('操作成功');
             }else{
            	 $("#notice").html("").hide();
                 showMessage("操作失败");
                 $(".audit").attr("disabled",false);
             }
         }
    });
}

function resetForm(orderId){
	currentOrderId=orderId;
	$("[name='payDate']").val("");
	$("input[name='backup']").each(function(){
        $(this).attr("checked",false);
    });
	$("[name='backupDate']").val("");
}

function pay(action){
	if(currentOrderId==null){
        return;
    }
    $(".pay").attr("disabled",true);
    $("#payButton").attr("disabled",true);
    var payDate = getElementValue($("[name='payDate']"));
    var backup = getElementValue($("[name='backup']"));
    var backupDate = getElementValue($("[name='backupDate']"));
    var error = "";
    if(payDate==""){
    	error += "支持日期不能为空<br>";
    }
    if(backup==""){
    	error += "支付凭证备份不能为空<br>";
    }else{
    	if(backup=="true" && backupDate==""){
    		error += "凭证备份日期不能为空<br>";
    	}
    }
    if(error!=""){
    	$("#suberror2").html(error).show();
    	$(".pay").attr("disabled",false);
        $("#payButton").attr("disabled",false);
    }else{
    	$("#suberror2").hide();
    	$("#subnotice2").html("操作进行中...").show();
        $.ajax({
            url: appRoot + "/expenseApply/pay/" + currentOrderId + "?payDate=" + payDate + "&backup=" + backup + "&backupDate=" + backupDate,
            type:'post',
            dataType:'json',
            success:function(msg){
                if(msg.result){
                    window.location.href= appRoot + '/expenseApply/' + action + '?message=' + encodeURIComponent('操作成功');
                }else{
                    $("#subnotice2").html("操作失败").show();
                }
                $(".pay").attr("disabled",false);
                $("#payButton").attr("disabled",false);
            }
       });
    }
}

function backward(action){
	if(currentOrderId==null){
		return;
	}
	var reason = $("#reason").val();
    if(!reason){
    	$("#suberror1").html("请填写退回原因").show();
    	return;
    }
	$("#subnotice1").html("操作进行中...").show();
	$("#suberror1").html("").hide();
	$(".bacward").attr("disabled",true);
	$("#backwardButton").attr("disabled",true);
	$.ajax({
         url: appRoot + "/expenseApply/backward/" + currentOrderId + "?reason=" +  encodeURIComponent(reason) + "&date=" + (new Date()).valueOf(),
         type:'post',
         dataType:'json',
         success:function(msg){
        	 if(msg.result){
        		 window.location.href= appRoot +'/expenseApply/' + action + '?message=' + encodeURIComponent('操作成功');
        	 }else{
        		 var message = msg.message;
        		 if(message==null){
        			 message = "操作失败";
        		 }
        		 $("#subnotice1").html("").hide();
        		 $("#suberror1").html(message).show();
        		 $(".bacward").attr("disabled",false);
        		 $("#backwardButton").attr("disabled",false);
        	 }
         }
	});
}